package org.learn.filter;

import org.apache.commons.lang3.StringUtils;
import org.learn.jwt.JwtUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JwtFilter implements Filter {


    /**
     * 排除链接
     */
    public List<String> excludes = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        {   //排除的连接（不进行过滤的连接）
            String tempExcludes = filterConfig.getInitParameter("excludes");
            if (StringUtils.isNotEmpty(tempExcludes)) {
                String[] url = tempExcludes.split(",");
                for (int i = 0; url != null && i < url.length; i++) {
                    excludes.add(url[i]);
                }
            }

        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        //url过滤
        if (handleExcludeURL(request, response)) {
            filterChain.doFilter(request, response);
            return;
        }
        //获取header中的token
        final String token = request.getHeader("jwtToken");
        if (token == null) {
            response.getWriter().write("token不存在！");
            return;
        }

        String userName = JwtUtil.getUsername(token);
        Map<String, Object> repMap = new HashMap<>();
        if (null == userName) {
            response.getWriter().write("token异常！");
            return;
        } else {
            repMap = JwtUtil.verify("token", userName);//验证token

            if (null != repMap && !repMap.isEmpty()) {
                userName = (String)repMap.get("username");
                //如果token合法，则放行
                request.getSession().setAttribute("userName", userName);

            } else {
                response.getWriter().write("token不合法！");
                return;
            }

        }
        filterChain.doFilter(req, res);

    }

    @Override
    public void destroy() {

    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {

        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : excludes) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }
}
